package com.tourism.service.impl;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tourism.core.common.utils.WebUtils;
import com.tourism.core.security.entity.LoginUser;
import com.tourism.core.security.util.SecurityHolderUtils;
import com.tourism.domain.dto.role.RoleAuthDTO;
import com.tourism.domain.dto.role.RoleQueryDTO;
import com.tourism.domain.entity.Role;
import com.tourism.domain.entity.RoleMenu;
import com.tourism.mapper.RoleMapper;
import com.tourism.mapper.RoleMenuMapper;
import com.tourism.service.MenuService;
import com.tourism.service.RoleService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 角色服务实现类
 *
 * @author lucky
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role>
        implements RoleService {

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Autowired
    private MenuService menuService;

    @Override
    public List<Long> getRoleAuth(Long roleId) {
        return baseMapper.getRoleAuth(roleId);
    }

    @Override
    public Page<Role> getPage(Integer pIndex, Integer pSize, RoleQueryDTO roleQueryDTO) {
        String name = roleQueryDTO.getName();
        Integer status = roleQueryDTO.getStatus();
        String code = roleQueryDTO.getCode();

        LambdaQueryWrapper<Role> lqw = new LambdaQueryWrapper<>();
        lqw.like(StrUtil.isNotBlank(name), Role::getName, name);
        lqw.like(StrUtil.isNotBlank(code), Role::getCode, code);
        lqw.eq(status != null, Role::getStatus, status);
        lqw.orderByDesc(Role::getUpdateTime);

        Page<Role> page = new Page<>(pIndex, pSize);

        return page(page, lqw);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean saveAuth(RoleAuthDTO roleAuthDTO) {
        // 删除角色权限
        roleMenuMapper.delete(new LambdaQueryWrapper<RoleMenu>().eq(RoleMenu::getRoleId, roleAuthDTO.getRoleId()));

        // 保存角色权限
        if (!roleAuthDTO.getMenuIds().isEmpty()) {
            roleMenuMapper.insertBatch(roleAuthDTO);
        }

        // 如果当前用户存在当前角色，则更新用户权限
        LoginUser loginUser = SecurityHolderUtils.getLoginUser();
        List<Long> roleIds = SecurityHolderUtils.getRoleIds();
        if (roleIds.contains(roleAuthDTO.getRoleId())) {

            Set<String> permissions = menuService.getAuth();

            loginUser.getUser().setPermissions(permissions);

            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            permissions.forEach(perm -> {
                if (perm != null && !perm.trim().isEmpty()) {
                    authorities.add(new SimpleGrantedAuthority(perm));
                }
            });
            loginUser.setAuthorities(authorities);

            HttpServletRequest request = WebUtils.getRequest();
            String token = request.getHeader("Authorization");
            request.getSession().setAttribute("login_user:" + token, loginUser);
        }

        return true;
    }

}




